package com.learning.platform.controller;

import com.learning.platform.dto.ApiResponse;
import com.learning.platform.dto.CertificateResponse;
import com.learning.platform.security.UserPrincipal;
import com.learning.platform.service.CertificateService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/certificates")
public class CertificateController {
    
    private final CertificateService certificateService;
    
    public CertificateController(CertificateService certificateService) {
        this.certificateService = certificateService;
    }
    
    @GetMapping("/{id}")
    public ApiResponse<CertificateResponse> getCertificate(@PathVariable Long id) {
        CertificateResponse response = certificateService.getCertificate(id);
        return ApiResponse.success(response);
    }
    
    @GetMapping("/my")
    public ApiResponse<Page<CertificateResponse>> getMyCertificates(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            Authentication auth) {
        
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        Page<CertificateResponse> certificates = certificateService.getUserCertificates(
            principal.getUserId(), PageRequest.of(page - 1, pageSize));
        return ApiResponse.success(certificates);
    }
    
    @GetMapping("/validate")
    public ApiResponse<CertificateResponse> validateCertificate(
            @RequestParam String certificateNumber,
            @RequestParam String verificationCode) {
        
        CertificateResponse response = certificateService.validateCertificate(certificateNumber, verificationCode);
        return ApiResponse.success(response, "证书验证成功");
    }
    
    @PostMapping("/{id}/revoke")
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResponse<Void> revokeCertificate(@PathVariable Long id, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        certificateService.revokeCertificate(id, principal);
        return ApiResponse.success(null, "证书已撤销");
    }
}

